package com.meiqiang.chat.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatServer {

    //定义属性
    private static Selector selector;
    private static ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //构造器
    //初始化
    public GroupChatServer(){
        try {
            //得到选择器
            selector = Selector.open();
            //得到ServerSocketChannel
            listenChannel = ServerSocketChannel.open();

            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置为非阻塞
            listenChannel.configureBlocking(false);
            //将channel注册到selector上面去
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //监听
    public void listen(){
        try{
            //循环处理
            while (true){
                int count = selector.select();
                if (count>0){//有相关的channel需要处理
                    //遍历得到selectorKeys集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        //监听到accept
                        if (key.isAcceptable()){//新的连接
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //注册到selector上面
                            sc.register(selector,SelectionKey.OP_READ);
                            //提示上线
                            System.out.println(sc.getRemoteAddress()+"上线了...");
                        }
                        if (key.isReadable()){//通道发生read事件，通道是可读的状态
                            //处理读
                            readData(key);
                        }

                        //将当前key删除，防止重复操作
                        iterator.remove();
                    }
                }else{
                    System.out.println("等待2秒，无任务需要处理");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

    //读取客户端消息
    private void readData(SelectionKey key){
        //定义一个socketChannel
        SocketChannel channel = null;
        try {
            //取到关联的channel
            channel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            //根据count值做处理
            if (count>0){
                //将缓冲区的数据转成字符串
                String msg = new String(buffer.array());
                System.out.println("form 客户端："+msg);
                //向其他客户端发送消息(排除自己)
                sendInfo2OtherClients(msg,channel);
            }
        }catch (Exception e){
            try {
                System.out.println(channel.getRemoteAddress()+" 离线了...");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
    }
    //转发消息给其他客户
    public void sendInfo2OtherClients(String msg,SocketChannel selfChannel) throws IOException {
        System.out.println("=======服务器转发消息了");
        //遍历 所有到selector上的socketChannel ，并排除自己
        for (SelectionKey key : selector.keys()){

            //通过key取出对应的socketChannel
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof  SocketChannel
                    && targetChannel != selfChannel){
                //转型
                SocketChannel desc = (SocketChannel)targetChannel;
                //将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //将buffer的数据写入到通道
                desc.write(buffer);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //创建服务器对象
        GroupChatServer chatServer = new GroupChatServer();
        new Thread(()->{
            chatServer.listen();
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            s = "【管理员】：" +s+"\n";
            chatServer.sendInfo2OtherClients(s,listenChannel.accept());
        }
    }
}
